package com.hxl.tech.gateway.auth.context;

import com.alibaba.fastjson.JSONObject;
import com.hxl.tech.gateway.auth.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    private static final List<String> ignoreUris = Arrays.asList("/auth/echo", "/auth/static/", "/auth/doc.html",
            "/auth/favicon.ico","/auth/error", "/auth/webjars", "/auth/swagger-resources",
            "/auth/oauth/authorize", "/auth/login", "/auth/oauth/token",  "/auth/.well-known/jwks.json");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = HttpUtil.getURI(request);
        for (String ignoreUri : ignoreUris) {
            if (uri.startsWith(ignoreUri)) {
                return true;
            }
        }

        RequestHolder.clear();
        RequestHolder.set(LocalDateTime.now());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        String uri = HttpUtil.getURI(request);
        for (String ignoreUri : ignoreUris) {
            if (uri.startsWith(ignoreUri)) {
                return;
            }
        }

        String requestParams = "";
        String requestMethod = request.getMethod();
        String remoteIp = HttpUtil.getIpAddr(request);
        String url = request.getRequestURI();

        if (request instanceof HttpServletRequestFilter.RequestWrapper) {
            HttpServletRequestFilter.RequestWrapper requestWrapper = (HttpServletRequestFilter.RequestWrapper) request;
            requestParams = HttpUtil.getBodyString(requestWrapper);
        }

        if ("GET".equals(requestMethod)) {
            Map parameterMap = HttpUtil.getParameterMapAll(request);
            if (parameterMap != null && parameterMap.size() > 0) {
                requestParams = JSONObject.toJSONString(parameterMap);
            }
        }

        log.info("接口{},method={},remoteIp={},requestParams={},耗时={}",
                url, requestMethod, remoteIp, requestParams,
                Duration.between(RequestHolder.get(), LocalDateTime.now()).toMillis());

        RequestHolder.clear();
    }
}
